package logic

import (
	"context"
	"errors"
	"goods_srv/goods"
	"goods_srv/internal/svc"
	"goods_srv/models/mysql"
	"goods_srv/models/redis"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddGoodsLogic {
	return &AddGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddGoodsLogic) AddGoods(in *goods.AddGoodsRequest) (*goods.AddGoodsResponse, error) {
	// todo: add your logic here and delete this line

	g := mysql.Goods{
		Name:  in.Name,
		Price: float64(in.Price),
		Stock: int(in.Stock),
	}
	err := g.Create()
	if err != nil {
		return nil, errors.New("商品添加失败")
	}
	//同步到缓存已队列的形式一排排展开
	redis.SyncGoodsStock(int(g.ID), g.Stock)
	return &goods.AddGoodsResponse{Id: int32(g.ID)}, nil
}
